const express = require("express");
const request = require("request");
const db = require("./db/index.js");

const app = express();
app.use(express.json());

let auth = null;

const noNeedAuth = ["/login"];

function success(data, msg) {
  return JSON.stringify({ code: 0, msg, data });
}
function error(msg, code = 1, data = null) {
  return JSON.stringify({ code, msg, data });
}

app.all("*", async function (req, res, next) {
  //设置跨域访问
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "*");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", " 3.2.1");
  res.header("Content-Type", "application/json;charset=utf-8");
  if (req.method.toLowerCase() == "options") {
    res.sendStatus(200); //让options尝试请求快速结束
  } else {
    if (noNeedAuth.indexOf(req.url) === -1) {
      if (!req.headers.token) {
        res.sendStatus(403);
        return;
      }
      auth = (await db.checkToken(req.headers.token))[0];
      if (!auth) {
        res.sendStatus(401);
        return;
      }
    }
    next();
  }
});

app.post("/login", (req, res) => {
  console.log(res);
  const { username, password } = req.body;
  db.login(username, password).then((user) => {
    if (user) {
      return res.end(success(user));
    }
    return res.end(error("账号或密码错误"));
  });
});

app.put("/master", (req, res) => {
  db.sqliteDB.executeSql(
    `UPDATE user SET main_account_id = ${req.body.id} WHERE id = ${auth.id}`
  );
  res.end(success());
});

app.get("/userinfo", (req, res) => {
  let userinfo = JSON.parse(JSON.stringify(auth));
  delete userinfo.password;
  res.end(success(userinfo));
});

app
  .route(/^\/account(\/\d+)?$/)
  .get(async (req, res) => {
    const id = req.url.match(/^\/account(\/(\d+))?$/)[2];
    let sql = `SELECT * FROM accounts WHERE uid = ${auth.id}`;
    if (id) {
      sql += ` AND id = ${id}`;
      return res.end(success((await db.sqliteDB.queryData(sql))[0]));
    }
    res.end(success(await db.sqliteDB.queryData(sql)));
  })
  .post(async (req, res) => {
    const { userid, brandname, nickname, cookie, enable } = req.body;
    const querySql = `SELECT * FROM accounts WHERE uid = ${auth.id} AND userid = ${userid}`;
    let account = (await db.sqliteDB.queryData(querySql))[0];
    if (account) {
      return res.end(error("账号已存在"));
    }
    db.sqliteDB.insertData(
      "insert into accounts(userid,brandname,nickname,cookie,enable,uid) values(?,?,?,?,?,?)",
      [[userid, brandname, nickname, cookie, enable, auth.id]]
    );

    account = (await db.sqliteDB.queryData(querySql))[0];
    if (!account) {
      return res.end(error("添加失败"));
    }
    if (!auth.main_account_id) {
      db.sqliteDB.executeSql(
        `UPDATE user SET main_account_id = ${account.id} WHERE id = ${auth.id}`
      );
    }
    return res.end(success());
  })
  .delete(async (req, res) => {
    const id = req.url.match(/^\/account(\/(\d+))?$/)[2];
    if (!id) {
      return res.sendStatus(404);
    }
    db.sqliteDB.executeSql(
      `DELETE FROM accounts WHERE uid = ${auth.id} AND id=${id}`
    );

    const rows = await db.sqliteDB.queryData(
      `SELECT * FROM accounts WHERE uid = ${auth.id}`
    );
    if (!rows.length) {
      db.sqliteDB.executeSql(
        `UPDATE user SET main_account_id = NULL WHERE id = ${auth.id}`
      );
    }
    res.end(success());
  })
  .put((req, res) => {
    const id = req.url.match(/^\/account(\/(\d+))?$/)[2];
    if (!id) {
      return res.sendStatus(404);
    }
    const sets = [];
    const where = `uid = ${auth.id} AND id = ${id}`;
    for (const key in req.body) {
      if (Object.hasOwnProperty.call(req.body, key)) {
        const element = req.body[key];
        sets.push(`${key} = '${req.body[key]}'`);
      }
    }
    const updateSql = `update accounts set ${sets.join(",")} where ${where}`;
    db.sqliteDB.executeSql(updateSql);
    res.end(success());
  });

app.all("*", (req, res) => {
  const uriHost = req.headers.domain.replace(/(.+)\/$/, "$1");
  const uriPath = req.url.replace(/^\/(.+)$/, "$1");
  const opt = {
    url: uriHost + "/" + uriPath,
    method: req.method,
    headers: {
      "Content-Type": "application/json",
      Cookie: req.headers.authorization,
    },
    body: JSON.stringify(req.body),
  };
  request(opt, (error, response, body) => {
    if (!error) {
      if (response.statusCode !== 200) {
        res.sendStatus(response.statusCode);
        return;
      }
      res.end(body);
    }
  });
});
app.listen(8099);
